"""
新的产品管理视图 - 集成变体管理
"""

from rest_framework import viewsets, filters, status
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from django_filters.rest_framework import DjangoFilterBackend
from drf_spectacular.utils import extend_schema, extend_schema_view
from django.db import transaction

from pecco_site.models import (
    Product, ProductVariant, ProductVariantImage, ProductOption,
    ProductOptionValue, ProductSpecification, Category
)
from ..serializers.product_new import (
    ProductListNewSerializer, ProductDetailNewSerializer,
    ProductVariantDetailSerializer, ProductOptionNestedSerializer
)
from ..filters import ProductFilter
from ..permissions import IsAdminUser


@extend_schema_view(
    list=extend_schema(summary='获取产品列表（新）', tags=['产品管理（新）']),
    retrieve=extend_schema(summary='获取产品详情（新）', tags=['产品管理（新）']),
    create=extend_schema(summary='创建产品（新）', tags=['产品管理（新）']),
    update=extend_schema(summary='更新产品（新）', tags=['产品管理（新）']),
    partial_update=extend_schema(summary='部分更新产品（新）', tags=['产品管理（新）']),
    destroy=extend_schema(summary='删除产品（新）', tags=['产品管理（新）']),
)
class ProductNewViewSet(viewsets.ModelViewSet):
    """新的产品管理 ViewSet - 集成变体管理"""
    queryset = Product.objects.all().prefetch_related(
        'categories', 'translations', 'variants',
        'variants__option_values', 'variants__images'
    )
    permission_classes = [IsAuthenticated, IsAdminUser]
    filter_backends = [DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter]
    filterset_class = ProductFilter
    search_fields = ['translations__name', 'id', 'variants__sku']
    ordering_fields = ['sort_order', 'created_at', 'updated_at', 'id']
    ordering = ['sort_order', '-created_at']

    def get_serializer_class(self):
        if self.action == 'list':
            return ProductListNewSerializer
        return ProductDetailNewSerializer

    @extend_schema(
        summary='获取可用的选项类型',
        tags=['产品管理（新）'],
        responses={200: ProductOptionNestedSerializer(many=True)}
    )
    @action(detail=False, methods=['get'])
    def available_options(self, request):
        """获取所有可用的选项类型（用于创建变体）"""
        options = ProductOption.objects.filter(is_active=True).prefetch_related(
            'values', 'translations', 'values__translations'
        )
        serializer = ProductOptionNestedSerializer(options, many=True, context={'request': request})
        return Response(serializer.data)

    @extend_schema(
        summary='获取分类列表（dog/cat）',
        tags=['产品管理（新）'],
        responses={
            200: {
                'type': 'array',
                'items': {
                    'type': 'object',
                    'properties': {
                        'id': {'type': 'integer'},
                        'slug': {'type': 'string'},
                        'name': {'type': 'string'}
                    }
                }
            }
        }
    )
    @action(detail=False, methods=['get'])
    def categories(self, request):
        """获取分类列表（简化为 dog/cat）"""
        categories = Category.objects.filter(
            slug__in=['dog', 'cat'],
            is_active=True
        ).prefetch_related('translations')
        
        result = []
        for cat in categories:
            trans = cat.translations.filter(locale='zh').first()
            if not trans:
                trans = cat.translations.filter(locale='en').first()
            
            result.append({
                'id': cat.id,
                'slug': cat.slug,
                'name': trans.name if trans else cat.slug
            })
        
        return Response(result)

    @extend_schema(
        summary='创建产品变体',
        tags=['产品管理（新）'],
        request=ProductVariantDetailSerializer,
        responses={201: ProductVariantDetailSerializer}
    )
    @action(detail=True, methods=['post'])
    def create_variant(self, request, pk=None):
        """为产品创建新变体"""
        product = self.get_object()
        
        data = request.data.copy()
        data['product'] = product.id
        
        serializer = ProductVariantDetailSerializer(data=data, context={'request': request})
        if serializer.is_valid():
            variant = serializer.save()
            return Response(
                ProductVariantDetailSerializer(variant, context={'request': request}).data,
                status=status.HTTP_201_CREATED
            )
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    @extend_schema(
        summary='更新产品变体',
        tags=['产品管理（新）'],
        request=ProductVariantDetailSerializer,
        responses={200: ProductVariantDetailSerializer}
    )
    @action(detail=True, methods=['patch'], url_path='variants/(?P<variant_id>[^/.]+)')
    def update_variant(self, request, pk=None, variant_id=None):
        """更新产品变体"""
        product = self.get_object()
        
        try:
            variant = ProductVariant.objects.get(id=variant_id, product=product)
        except ProductVariant.DoesNotExist:
            return Response(
                {'error': '变体不存在'},
                status=status.HTTP_404_NOT_FOUND
            )
        
        serializer = ProductVariantDetailSerializer(
            variant, data=request.data, partial=True, context={'request': request}
        )
        if serializer.is_valid():
            variant = serializer.save()
            return Response(
                ProductVariantDetailSerializer(variant, context={'request': request}).data
            )
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    @extend_schema(
        summary='删除产品变体',
        tags=['产品管理（新）'],
        responses={204: None}
    )
    @action(detail=True, methods=['delete'], url_path='variants/(?P<variant_id>[^/.]+)')
    def delete_variant(self, request, pk=None, variant_id=None):
        """删除产品变体"""
        product = self.get_object()
        
        try:
            variant = ProductVariant.objects.get(id=variant_id, product=product)
        except ProductVariant.DoesNotExist:
            return Response(
                {'error': '变体不存在'},
                status=status.HTTP_404_NOT_FOUND
            )
        
        variant.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)

    @extend_schema(
        summary='上传变体图片',
        tags=['产品管理（新）'],
        request={
            'multipart/form-data': {
                'type': 'object',
                'properties': {
                    'image': {'type': 'string', 'format': 'binary'},
                    'sort_order': {'type': 'integer'},
                    'is_primary': {'type': 'boolean'}
                }
            }
        },
        responses={201: {'type': 'object'}}
    )
    @action(detail=True, methods=['post'], url_path='variants/(?P<variant_id>[^/.]+)/images')
    def upload_variant_image(self, request, pk=None, variant_id=None):
        """上传变体图片"""
        product = self.get_object()
        
        try:
            variant = ProductVariant.objects.get(id=variant_id, product=product)
        except ProductVariant.DoesNotExist:
            return Response(
                {'error': '变体不存在'},
                status=status.HTTP_404_NOT_FOUND
            )
        
        image = request.FILES.get('image')
        if not image:
            return Response(
                {'error': '请上传图片'},
                status=status.HTTP_400_BAD_REQUEST
            )
        
        sort_order = request.data.get('sort_order', 0)
        is_primary = request.data.get('is_primary', False)
        
        variant_image = ProductVariantImage.objects.create(
            variant=variant,
            image=image,
            sort_order=sort_order,
            is_primary=is_primary
        )
        
        return Response({
            'id': variant_image.id,
            'image_url': request.build_absolute_uri(variant_image.image.url),
            'sort_order': variant_image.sort_order,
            'is_primary': variant_image.is_primary
        }, status=status.HTTP_201_CREATED)

    @extend_schema(
        summary='删除变体图片',
        tags=['产品管理（新）'],
        responses={204: None}
    )
    @action(
        detail=True, methods=['delete'],
        url_path='variants/(?P<variant_id>[^/.]+)/images/(?P<image_id>[^/.]+)'
    )
    def delete_variant_image(self, request, pk=None, variant_id=None, image_id=None):
        """删除变体图片"""
        product = self.get_object()
        
        try:
            variant = ProductVariant.objects.get(id=variant_id, product=product)
            image = ProductVariantImage.objects.get(id=image_id, variant=variant)
        except (ProductVariant.DoesNotExist, ProductVariantImage.DoesNotExist):
            return Response(
                {'error': '图片不存在'},
                status=status.HTTP_404_NOT_FOUND
            )
        
        image.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)

    @extend_schema(
        summary='批量删除产品',
        tags=['产品管理（新）'],
        request={
            'application/json': {
                'type': 'object',
                'properties': {
                    'ids': {
                        'type': 'array',
                        'items': {'type': 'integer'}
                    }
                }
            }
        }
    )
    @action(detail=False, methods=['post'])
    def bulk_delete(self, request):
        """批量删除产品"""
        ids = request.data.get('ids', [])
        if not ids:
            return Response(
                {'error': '请提供要删除的产品 ID'},
                status=status.HTTP_400_BAD_REQUEST
            )
        
        deleted_count, _ = Product.objects.filter(id__in=ids).delete()
        return Response({
            'message': f'成功删除 {deleted_count} 个产品',
            'deleted_count': deleted_count
        })

    @extend_schema(
        summary='切换产品激活状态',
        tags=['产品管理（新）']
    )
    @action(detail=True, methods=['patch'])
    def toggle_active(self, request, pk=None):
        """切换产品激活状态"""
        product = self.get_object()
        product.is_active = not product.is_active
        product.save()
        return Response({'is_active': product.is_active})

